// Copyright Epic Games, Inc. All Rights Reserved.

#include "zencore/testutils.h"

#if ZEN_WITH_TESTS

#	include <zencore/session.h>
#	include "zencore/string.h"

#	include <atomic>

namespace zen {

static std::atomic<int> Sequence{0};

std::filesystem::path
CreateTemporaryDirectory()
{
	std::error_code Ec;

	std::filesystem::path DirPath = std::filesystem::temp_directory_path() / GetSessionIdString() / IntNum(++Sequence).c_str();
	std::filesystem::remove_all(DirPath, Ec);
	std::filesystem::create_directories(DirPath);

	return DirPath;
}

ScopedTemporaryDirectory::ScopedTemporaryDirectory() : m_RootPath(CreateTemporaryDirectory())
{
}

ScopedTemporaryDirectory::ScopedTemporaryDirectory(std::filesystem::path Directory) : m_RootPath(Directory)
{
	std::error_code Ec;
	std::filesystem::remove_all(Directory, Ec);
	std::filesystem::create_directories(Directory);
}

ScopedTemporaryDirectory::~ScopedTemporaryDirectory()
{
	std::error_code Ec;
	std::filesystem::remove_all(m_RootPath, Ec);
}

IoBuffer
CreateRandomBlob(uint64_t Size)
{
	static uint64_t Seed{0x7CEBF54E45B9F5D1};
	auto			Next = [](uint64_t& seed) {
		   uint64_t z = (seed += UINT64_C(0x9E3779B97F4A7C15));
		   z		  = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
		   z		  = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
		   return z ^ (z >> 31);
	};

	IoBuffer  Data(Size);
	uint64_t* DataPtr = reinterpret_cast<uint64_t*>(Data.MutableData());
	while (Size > sizeof(uint64_t))
	{
		*DataPtr++ = Next(Seed);
		Size -= sizeof(uint64_t);
	}
	uint64_t ByteNext	 = Next(Seed);
	uint8_t* ByteDataPtr = reinterpret_cast<uint8_t*>(DataPtr);
	while (Size > 0)
	{
		*ByteDataPtr++ = static_cast<uint8_t>(ByteNext & 0xff);
		ByteNext >>= 8;
		Size--;
	}
	return Data;
};

}  // namespace zen

#endif	// ZEN_WITH_TESTS
